﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows;
using System.Windows.Media;
using TextEditor.TextBoxInner.DrawingElements;

namespace TextEditor.TextBoxInner.Layers
{
	internal abstract class LayerBase<T> : UIElement where T: DrawingVisual
	{
		private readonly DrawingElementFactory<T> _elementCreator;
		protected readonly List<T> Children = new List<T>(50);

		protected LayerBase(DrawingElementFactory<T> elementCreator)
		{
			if (elementCreator == null) 
				throw new ArgumentNullException("elementCreator");

			_elementCreator = elementCreator;

			IsHitTestVisible = false;
		}

		protected override Visual GetVisualChild(int index)
		{
			return Children[index];
		}

		protected override int VisualChildrenCount
		{
			get { return Children.Count; }
		}

		internal void SetLeft(double leftOffset)
		{
			SetOffset(leftOffset, VisualOffset.Y);
		}

		protected double GetLeft()
		{
			return VisualOffset.X;
		}

		internal void SetTop(double topOffset)
		{
			SetOffset(VisualOffset.X, topOffset);
		}

		internal void SetOffset(double x, double y)
		{
			VisualOffset = new Vector(x, y);
		}

		internal void SetLinesCount(int linesCount)
		{
			if (linesCount == Children.Count)
				return;

			if (linesCount > Children.Count)
			{
				for (int index = Children.Count; index < linesCount; index++)
				{
					T item = _elementCreator.Create();

					Children.Add(item);
					AddVisualChild(item);
				}
			}
			else
			{
				for (int index = Children.Count - 1; index >= linesCount; index--)
				{
					T item = Children[index];

					Children.RemoveAt(index);
					RemoveVisualChild(item);
				}
			}
		}
	}
}
